package com.hty.accountbook;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class MainActivity extends Activity {
    EditText editText_search;
    ImageButton imageButton_clear;
    ListView listView;
    SimpleCursorAdapter adapter;
    InputMethodManager IMM;
    SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    int position1 = 0;
    String[] types = new String[]{"收支", "支出", "收入"};
    String[] types1 = new String[]{"支出", "收入"};
    ArrayAdapter<String> adapter_type;
    ArrayAdapter<String> adapter_type1;
    Spinner spinner_year, spinner_type;
    TextView textView_sum;
    String uid, username, tableName;

    String[] from = { "_id", "time", "type", "cash", "event" };
    int[] to = { R.id.textView_id, R.id.textView_username, R.id.textView_type, R.id.textView_cash, R.id.textView_event };
    SimpleCursorAdapter.ViewBinder viewBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = getIntent();
        uid = intent.getStringExtra("uid");
        username = intent.getStringExtra("username");
        tableName = "account" + uid;

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        IMM = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);

        viewBinder = new SimpleCursorAdapter.ViewBinder() {
            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
                //Log.e(Thread.currentThread().getStackTrace()[2] + "", view.toString() + columnIndex);
                if (view.getId() == R.id.textView_username) {
                    Date date = new Date(cursor.getLong(columnIndex));
                    ((TextView)view).setText(SDF.format(date));
                    return true;
                } else if (view.getId() == R.id.textView_type) {
                    int type = cursor.getInt(columnIndex);
                    if (type == 0)
                        ((TextView)view).setText("支出");
                    else
                        ((TextView)view).setText("收入");
                    return true;
                } else if (view.getId() == R.id.textView_cash) {
                    ((TextView)view).setText(String.format("%.2f", cursor.getFloat(columnIndex)));
                    return true;
                }
                return false;
            }
        };

        spinner_year = (Spinner) findViewById(R.id.spinner_year);
        setSpinnerYear();
        spinner_year.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Log.e(Thread.currentThread().getStackTrace()[2] + "", "spin_year: " + arg2);
                queryByYearType();
            }
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        spinner_type = (Spinner) findViewById(R.id.spinner_type);
        adapter_type = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, types);
        spinner_type.setAdapter(adapter_type);
        spinner_type.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Log.e(Thread.currentThread().getStackTrace()[2] + "", "spin_type: " + arg2);
                queryByYearType();
            }
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        adapter_type1 = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, types1);

        editText_search = (EditText) findViewById(R.id.editText_search);
        editText_search.addTextChangedListener(new TextWatcher(){
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {
                    imageButton_clear.setVisibility(View.GONE);
                } else {
                    imageButton_clear.setVisibility(View.VISIBLE);
                }
                search(s.toString());
            }
        });
        imageButton_clear = (ImageButton) findViewById(R.id.imageButton_clear);
        imageButton_clear.setVisibility(View.GONE);
        textView_sum = (TextView) findViewById(R.id.textView_sum);
        listView = (ListView) findViewById(R.id.listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                IMM.hideSoftInputFromWindow(editText_search.getWindowToken(), 0);
                final String stime = ((TextView) view.findViewById(R.id.textView_username)).getText().toString();
                final String cash = ((TextView) view.findViewById(R.id.textView_cash)).getText().toString();
                final String event = ((TextView) view.findViewById(R.id.textView_event)).getText().toString();
                final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setIcon(android.R.drawable.ic_menu_info_details);
                String title = "";
                Date date = new Date();
                try {
                    date = SDF.parse(stime);
                } catch (Exception e){
                    Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
                }
                Date date1 = new Date();
                long ms = Math.abs(date1.getTime() - date.getTime());
                if (Math.floor((double)ms/(1000L*60L*60L*24L*365L)) >= 1) {
                    title += ms/(1000L*60L*60L*24L*365L) + "年";
                } else if (Math.floor((double)ms/(1000L*60L*60L*24L*30L)) >= 1) {
                    title += ms/(1000L*60L*60L*24L*30L) + "月";
                } else if (Math.floor((double)ms/(1000*60*60*24)) >= 1) {
                    title += ms/(1000*60*60*24) + "天";
                }
                if (date.before(date1))
                    title += "前";
                else
                    title += "后";
                if (ms <= 1000*60*60*24) {
                    title = "一天内";
                }
                builder.setTitle(title);
                builder.setMessage(stime + "\n" + cash + "\n" + event);
                builder.setPositiveButton("复制", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager CM = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clipData = ClipData.newPlainText("text", stime + "\n" + cash + "\n" + event);
                        CM.setPrimaryClip(clipData);
                        Toast.makeText(getApplicationContext(), "内容已复制", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("搜索", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                        builder1.setIcon(android.R.drawable.ic_menu_search);
                        builder1.setTitle("搜索");
                        final EditText editText = new EditText(MainActivity.this);
                        editText.setText(event);
                        builder1.setView(editText);
                        builder1.setPositiveButton("搜索", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                IMM.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_WEB_SEARCH);
                                intent.putExtra(SearchManager.QUERY, editText.getText().toString());
                                startActivity(intent);
                            }
                        });
                        builder1.create().show();
                    }
                });
                builder.setNeutralButton("分享", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_SEND);
                        intent.putExtra(Intent.EXTRA_TEXT, stime + "\n" + cash + "\n" + event);
                        intent.setType("text/plain");
                        startActivity(Intent.createChooser(intent, "分享到"));
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });
        listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
                //AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
                //String title = ((TextView) info.targetView.findViewById(R.id.title)).getText().toString();
                //menu.setHeaderTitle(title);
                menu.add(0, 0, 0, "复制");
                menu.add(0, 1, 1, "分享");
                menu.add(0, 2, 2, "修改");
                menu.add(0, 3, 3, "删除");
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "添加账单");
        menu.add(0, 1, 1, "导出HTML");
        menu.add(0, 2, 2, "导出CSV");
        menu.add(0, 3, 3, "返回");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int item_id = item.getItemId();
        switch (item_id) {
            case 0:
                LayoutInflater layoutInflater = LayoutInflater.from(this);
                View view = layoutInflater.inflate(R.layout.cash_edit, null);
                final EditText editText_cash = (EditText) view.findViewById(R.id.editText_cash);
                final EditText editText_event = (EditText) view.findViewById(R.id.editText_event);
                final DatePicker datePicker = (DatePicker) view.findViewById(R.id.datePicker);
                final TimePicker timePicker = (TimePicker) view.findViewById(R.id.timePicker);
                timePicker.setIs24HourView(true);
                final Spinner spinner_type1 = (Spinner) view.findViewById(R.id.spinner_type);
                spinner_type1.setAdapter(adapter_type1);
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setIcon(android.R.drawable.ic_menu_add);
                builder.setTitle("添加账单");
                builder.setView(view);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        IMM.hideSoftInputFromWindow(editText_event.getWindowToken(), 0);
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        int hour = timePicker.getCurrentHour();
                        int minute = timePicker.getCurrentMinute();
                        Date date = new Date(year - 1900, month, day, hour, minute);
                        String stime = SDF.format(date);
                        Log.e(Thread.currentThread().getStackTrace()[2] + "", stime);
                        Log.e(Thread.currentThread().getStackTrace()[2] + "", "spinner_type" + spinner_type.getSelectedItemId());
                        String scash = editText_cash.getText().toString();
                        String event = editText_event.getText().toString();
                        Field field = null;
                        try {
                            //通过反射获取dialog中的私有属性mShowing
                            field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                            field.setAccessible(true);//设置该属性可以访问
                        } catch (Exception e) {
                            Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
                        }
                        if (!scash.equals("") && (!event.equals(""))) {
                            long type = spinner_type1.getSelectedItemId();
                            float cash = Float.parseFloat(scash);
                            if(type == 0 && cash > 0)//支出为负
                                cash = -cash;
                            DBHelper dbHelper = new DBHelper(getApplicationContext());
                            ContentValues values = new ContentValues();
                            values.put("time", date.getTime());
                            values.put("type", type);
                            values.put("cash", cash);
                            values.put("event", event);
                            long r = dbHelper.insert(tableName, values);
                            if (r != -1) {
                                search(editText_search.getText().toString());
                                try {
                                    //关闭
                                    field.set(dialog, true);
                                    dialog.dismiss();
                                } catch (Exception ex) {
                                    Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT);
                                }
                            } else {
                                Toast.makeText(getApplicationContext(), "记账失败！", Toast.LENGTH_SHORT);
                            }
                        } else {
                            if (scash.equals("")) {
                                editText_cash.setError("金额不能为空！");
                            }
                            if (event.equals("")) {
                                editText_event.setError("事项不能为空！");
                            }
                            try {
                                //设置dialog不可关闭
                                field.set(dialog, false);
                                dialog.dismiss();
                            } catch (Exception ex) {
                                Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT);
                            }
                        }
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        IMM.hideSoftInputFromWindow(editText_event.getWindowToken(), 0);
                        Field field = null;
                        try {
                            //通过反射获取dialog中的私有属性mShowing
                            field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                            field.setAccessible(true);//设置该属性可以访问
                        } catch (Exception ex) {
                        }
                        try {
                            field.set(dialog, true);
                            dialog.dismiss();
                        } catch (Exception ex) {
                        }
                    }
                });
                builder.create().show();
                break;
            case 1:
                String s = "<html>\n<head>\n<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'/>\n<title>账目</title>\n<style>\ntable { margin:auto; border-collapse:collapse; }\nth, td { border:1px solid black; padding:5px; white-space:nowrap; }\ntd:nth-child(1), td:nth-child(2), td:nth-child(3) { text-align:center; }\ntd:nth-child(4) { text-align:right; }\ntd:nth-child(5) { white-space:normal; }\n</style>\n</head>\n<body>\n<h2 align='center'>" + username + "的" + editText_search.getText().toString() + "账目</h2>\n<table>\n<tr><th>序号</th><th>时间</th><th>类型</th><th>金额(元)</th><th>事项</th></tr>\n";
                for (int i=0; i<adapter.getCount(); i++) {
                    LinearLayout layout = (LinearLayout) listView.getAdapter().getView(i, null, null);
                    TextView textView_time = (TextView) layout.findViewById(R.id.textView_username);
                    TextView textView_type = (TextView) layout.findViewById(R.id.textView_type);
                    TextView textView_cash = (TextView) layout.findViewById(R.id.textView_cash);
                    TextView textView_event = (TextView) layout.findViewById(R.id.textView_event);
                    s = s + "<tr><td>" + (i + 1) + "</td><td>" + textView_time.getText().toString() + "</td><td>" + textView_type.getText().toString() + "</td><td>" + textView_cash.getText().toString() + "</td><td>" + textView_event.getText().toString() + "</td></tr>\n";
                }
                s = s + "<tr><td colspan='3'>合计</td><td>" + textView_sum.getText().toString() + "</td><td></td></table>\n</body>\n</html>";
                String filename = username + "的" + editText_search.getText().toString() + "账目.htm";
                writeFile(filename, s);
                break;
            case 2:
                s = username + "的" + editText_search.getText().toString() + "账目\r\n时间,类型,金额,事项\r\n";
                for (int i=0; i<adapter.getCount(); i++) {
                    LinearLayout layout = (LinearLayout) listView.getAdapter().getView(i, null, null);
                    TextView textView_time = (TextView) layout.findViewById(R.id.textView_username);
                    TextView textView_type = (TextView) layout.findViewById(R.id.textView_type);
                    TextView textView_cash = (TextView) layout.findViewById(R.id.textView_cash);
                    TextView textView_event = (TextView) layout.findViewById(R.id.textView_event);
                    s = s + textView_time.getText().toString() + "," + textView_type.getText().toString() +"," + textView_cash.getText().toString().replace("\n", " ").replace(",","，") + "," + textView_event.getText().toString().replace("\n", " ").replace(",","，") + "\r\n";
                }
                filename = username + "的" + editText_search.getText().toString() + "账目.csv";
                writeFile(filename, s);
                break;
            case 3:
                finish();
                break;
        }
        return true;
    }

    void search(String s) {
        //IMM.hideSoftInputFromWindow(editText_search.getWindowToken(), 0);
        DBHelper helper = new DBHelper(this);
        Cursor cursor1 = helper.query(tableName, s);
        int count = cursor1.getCount();
        setTitle(username + "的" + editText_search.getText().toString() + "账目 " + count);
        adapter = new SimpleCursorAdapter(this, R.layout.item_cash, cursor1, from, to, 0);
        adapter.setViewBinder(viewBinder);
        listView.setAdapter(adapter);
        calcSum();
    }

    void calcSum() {
        float sum = 0;
        for (int i=0; i<adapter.getCount(); i++) {
            LinearLayout layout = (LinearLayout) listView.getAdapter().getView(i, null, null);
            TextView textView_cash = (TextView) layout.findViewById(R.id.textView_cash);
            float cash = Float.parseFloat(textView_cash.getText().toString());
            sum += cash;
        }
        textView_sum.setText(String.format("%.2f", sum));
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        final String sid = ((TextView) menuInfo.targetView.findViewById(R.id.textView_id)).getText().toString();
        String stime = ((TextView) menuInfo.targetView.findViewById(R.id.textView_username)).getText().toString();
        final String stype = ((TextView) menuInfo.targetView.findViewById(R.id.textView_type)).getText().toString();
        String cash = ((TextView) menuInfo.targetView.findViewById(R.id.textView_cash)).getText().toString();
        String event = ((TextView) menuInfo.targetView.findViewById(R.id.textView_event)).getText().toString();
        position1 = menuInfo.position;
        switch (item.getItemId()) {
            case 0:
                ClipboardManager CM = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                CM.setPrimaryClip(ClipData.newPlainText("text", stime + "\n" + cash + "\n" + event));
                Toast.makeText(getApplicationContext(), "内容已复制", Toast.LENGTH_SHORT).show();
                break;
            case 1:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_TEXT, stime + "\n" + cash + "\n" + event);
                intent.setType("text/plain");
                startActivity(Intent.createChooser(intent, "分享到"));
                break;
            case 2:
                LayoutInflater layoutInflater = LayoutInflater.from(this);
                View view = layoutInflater.inflate(R.layout.cash_edit, null);
                final EditText editText_cash = (EditText) view.findViewById(R.id.editText_cash);
                final EditText editText_event = (EditText) view.findViewById(R.id.editText_event);
                final DatePicker datePicker = (DatePicker) view.findViewById(R.id.datePicker);
                final TimePicker timePicker = (TimePicker) view.findViewById(R.id.timePicker);
                timePicker.setIs24HourView(true);
                final Spinner spinner_type1 = (Spinner) view.findViewById(R.id.spinner_type);
                spinner_type1.setAdapter(adapter_type1);
                Date date;
                try {
                    date = SDF.parse(stime);
                    datePicker.init(date.getYear() + 1900, date.getMonth(), date.getDate(), null);
                    timePicker.setCurrentHour(date.getHours());
                    timePicker.setCurrentMinute(date.getMinutes());
                } catch (Exception e){
                    Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT);
                }
                int type = adapter_type1.getPosition(stype);
                spinner_type1.setSelection(type);
                editText_cash.setText(cash);
                editText_event.setText(event);
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setIcon(android.R.drawable.ic_menu_edit);
                builder.setTitle("修改账目");
                builder.setView(view);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        IMM.hideSoftInputFromWindow(editText_event.getWindowToken(), 0);
                        String scash = editText_cash.getText().toString();
                        String event = editText_event.getText().toString();
                        Field field = null;
                        try {
                            //通过反射获取dialog中的私有属性mShowing
                            field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                            field.setAccessible(true);//设置该属性可以访问
                        } catch (Exception e) {
                            Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
                        }
                        if (!scash.equals("") && !event.equals("")) {
                            int year =  datePicker.getYear();
                            int month = datePicker.getMonth();
                            int day = datePicker.getDayOfMonth();
                            int hour = timePicker.getCurrentHour();
                            int minute = timePicker.getCurrentMinute();
                            Date date = new Date(year - 1900, month, day, hour, minute);
                            long type = spinner_type1.getSelectedItemId();
                            float cash = Float.parseFloat(scash);
                            if (type == 0 && cash > 0)//支出为负
                                cash = -cash;
                            DBHelper dbHelper = new DBHelper(getApplicationContext());
                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                            ContentValues values = new ContentValues();
                            values.put("time", date.getTime());
                            values.put("type", type);
                            values.put("cash", cash);
                            values.put("event", event);
                            db.update(tableName, values, "_id = " + sid, null);
                            search(editText_search.getText().toString());
                            listView.setSelection(position1);
                            try {
                                //关闭
                                field.set(dialog, true);
                                dialog.dismiss();
                            } catch (Exception e) {
                                Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
                            }
                        } else {
                            if (scash.equals("")){
                                editText_cash.setError("金额不能为空！");
                            }
                            if (event.equals("")){
                                editText_event.setError("事项不能为空！");
                            }
                            try {
                                //设置dialog不可关闭
                                field.set(dialog, false);
                                dialog.dismiss();
                            } catch (Exception e) {
                                Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
                            }
                        }
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        try {
                            //通过反射获取dialog中的私有属性mShowing
                            field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                            field.setAccessible(true);//设置该属性可以访问
                        } catch (Exception ex) {
                        }
                        try {
                            field.set(dialog, true);
                            dialog.dismiss();
                        } catch (Exception e) {
                            Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
                        }
                    }
                });
                builder.create().show();
                break;
            case 3:
                new AlertDialog.Builder(MainActivity.this)
                        .setIcon(android.R.drawable.stat_sys_warning)
                        .setTitle("删除操作")
                        .setMessage("此步骤不可还原，确定删除" + sid + "？\n" + stime + "\n" + cash + "\n" + event)
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,	int which) {
                                DBHelper dbHelper = new DBHelper(getApplicationContext());
                                dbHelper.del(tableName, sid);
                                search(editText_search.getText().toString());
                                listView.setSelection(position1);
                            }
                        })
                        .setNegativeButton("否", null)
                        .show();
                break;
        }
        return true;
    }

    public void clear(View view){
        editText_search.setText("");
    }

    void writeFile(String filename, String s) {
        File file = new File(UserActivity.dir, filename);
        try {
            BufferedWriter BW = new BufferedWriter(new FileWriter(file, false)); //false覆盖
            if(filename.endsWith(".csv")){
                BW.write('\ufeff'); // Excel通过文件的BOM头来判断文件编码
                BW.flush();
            }
            BW.write(s);
            BW.flush();
            MediaScannerConnection.scanFile(MainActivity.this, new String[]{ file.getAbsolutePath() }, null, null);
            Toast.makeText(getApplicationContext(), "写文件 " + UserActivity.dir + File.separator + filename + " 成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
        }
    }

    void setSpinnerYear() {
        ArrayList<String> list_year = new ArrayList<>();
        list_year.add("年份");
        DBHelper helper = new DBHelper(this);
        Cursor cursor = helper.timeMin(tableName);
        cursor.moveToFirst();
        //Log.e(Thread.currentThread().getStackTrace()[2] + "", cursor.getLong(cursor.getColumnIndex("time")) + "");
        if (cursor.getCount() > 0) {
            Date date = new Date(cursor.getLong(cursor.getColumnIndex("time")));
            cursor.close();
            int year = date.getYear() + 1900;
            //Log.e(Thread.currentThread().getStackTrace()[2] + "", year + "");
            Date date1 = new Date();
            int year1 = date1.getYear() + 1900;
            int d = year1 - year;
            for (int i = 0; i <= d; i++) {
                list_year.add(year1 - i + "");
            }
        }
        ArrayAdapter adapter_year = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, list_year);
        spinner_year.setAdapter(adapter_year);
    }

    void queryByYearType() {
        IMM.hideSoftInputFromWindow(editText_search.getWindowToken(), 0);
        String year = spinner_year.getSelectedItem().toString();
        String type = spinner_type.getSelectedItem().toString();
        long type_id = spinner_type.getSelectedItemId();
        DBHelper helper = new DBHelper(MainActivity.this);
        Cursor cursor = helper.queryByYearType(tableName, year, type_id -1, editText_search.getText().toString());
        int count = cursor.getCount();
        if (spinner_year.getSelectedItemId() == 0)
            year = "";
        else
            year += "年";
        setTitle(username + " " + year + " " + type + "账目 " + count);
        adapter = new SimpleCursorAdapter(MainActivity.this, R.layout.item_cash, cursor, from, to, 0);
        adapter.setViewBinder(viewBinder);
        listView.setAdapter(adapter);
        calcSum();
    }

}